package com.ruoyi.web.controller.prt;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.prt.domain.PrtUserDoc;
import com.ruoyi.prt.domain.vo.PrtUserDocVO;
import com.ruoyi.prt.service.IPrtUserDocService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.utils.file.FileUploadUtils.getExtension;

/**
 * 用户文档Controller
 *
 * @author xiaobo Yan
 * @date 2021-03-31
 */
@RestController
@RequestMapping("/prt/doc")
public class PrtUserDocController extends BaseController {
    @Autowired
    private IPrtUserDocService prtUserDocService;

    /**
     * 查询用户文档列表
     */
    @PreAuthorize("@ss.hasPermi('system:doc:list')")
    @GetMapping("/list")
    public TableDataInfo list(PrtUserDoc prtUserDoc) {
        startPage();
        List<PrtUserDoc> list = prtUserDocService.selectPrtUserDocList(prtUserDoc);
        return getDataTable(list);
    }

    /**
     * 导出用户文档列表
     */
    @PreAuthorize("@ss.hasPermi('system:doc:export')")
    @Log(title = "用户文档", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PrtUserDoc prtUserDoc) {
        List<PrtUserDoc> list = prtUserDocService.selectPrtUserDocList(prtUserDoc);
        ExcelUtil<PrtUserDoc> util = new ExcelUtil<PrtUserDoc>(PrtUserDoc.class);
        return util.exportExcel(list, "doc");
    }

    /**
     * 获取用户文档详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:doc:query')")
    @GetMapping(value = "/{docId}")
    public AjaxResult getInfo(@PathVariable("docId") String docId) {
        return AjaxResult.success(prtUserDocService.selectPrtUserDocById(docId));
    }

    /**
     * 新增用户文档
     */
    @PreAuthorize("@ss.hasPermi('system:doc:add')")
    @Log(title = "用户文档", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PrtUserDoc prtUserDoc) {
        return toAjax(prtUserDocService.insertPrtUserDoc(prtUserDoc));
    }

    /**
     * 修改用户文档
     */
    @PreAuthorize("@ss.hasPermi('system:doc:edit')")
    @Log(title = "用户文档", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PrtUserDoc prtUserDoc) {
        return toAjax(prtUserDocService.updatePrtUserDoc(prtUserDoc));
    }

    /**
     * 删除用户文档
     */
    @PreAuthorize("@ss.hasPermi('system:doc:remove')")
    @Log(title = "用户文档", businessType = BusinessType.DELETE)
    @DeleteMapping("/{docIds}")
    public AjaxResult remove(@PathVariable String[] docIds) {
        return toAjax(prtUserDocService.deletePrtUserDocByIds(docIds));
    }

    @PreAuthorize("@ss.hasRole('mobile')")
    @Log(title = "获取我的文档", businessType = BusinessType.SELECT)
    @GetMapping("/myFiles")
    public AjaxResult myFiles(PrtUserDocVO params) {
        Long userid = SecurityUtils.getUserId();
        params.setCreated(userid);
        return AjaxResult.success().setData(prtUserDocService.selectPrtUserDocByCreated(params));
    }

    /**
     * 上传文档
     */
    @Log(title = "上传文档", businessType = BusinessType.UPLOAD_FILE)
    @PostMapping("/upfile")
    @PreAuthorize("@ss.hasRole('mobile')")
    public AjaxResult upfile(MultipartFile file, @Param("filename") String filename) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String extension = getExtension(file);
            PrtUserDoc prtUserDoc = new PrtUserDoc();
            prtUserDoc.setDocName(filename);
            prtUserDoc.setCreated(SecurityUtils.getUserId());
            prtUserDoc.setSaveName(fileName);
            prtUserDoc.setAddress(fileName);
            prtUserDoc.setDocFormat(extension);
            prtUserDoc.setContentType(file.getContentType());
            prtUserDoc.setIsEnable(1);
            prtUserDoc.setSize(file.getSize());
            prtUserDoc.setCreatedName(SecurityUtils.getUsername());
            prtUserDoc.setSaveType("file");
            prtUserDoc.setDocId(StringUtils.getUUID());
            prtUserDoc.setCreatedTime(new Date());
            prtUserDocService.insertPrtUserDoc(prtUserDoc);
            return AjaxResult.success().setData(prtUserDoc);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    @Log(title = "下载用户文件", businessType = BusinessType.DOWNLOAD_FILE)
    @GetMapping("/file/{id}")
    public void getFile(@PathVariable String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        PrtUserDoc doc = prtUserDocService.selectPrtUserDocById(id);
        if (StringUtils.isEmpty(doc.getPdfName())){
            prtUserDocService.convertToPdf(doc);
        }
        String pdfPath = FileUploadUtils.getUploadDir(doc.getPdfName());
        byte[] bytes = FileUploadUtils.fileToByteArray(pdfPath);
        if (bytes != null){
            response.setContentType("application/pdf;charset=utf-8");
            String docName = doc.getDocName();
            String filename = docName.substring(0,docName.lastIndexOf('.')) + ".pdf";
            String userAgent = request.getHeader("user-agent");
            boolean b = userAgent.contains("Edge")
                    && (userAgent.contains("Firefox") || userAgent.contains("Chrome") || userAgent.contains("Safari"));
            if (b) {
                filename = new String((filename).getBytes(), StandardCharsets.ISO_8859_1);
            } else {
                //其他浏览器
                filename = URLEncoder.encode(filename, "UTF8");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.getOutputStream().write(bytes);
        }
    }
}
